<?php

namespace Partner\Controller;

use Utuo\BackgroundController;

class ThemeController extends BackgroundController {
	
	private $model = null;
	
	public function _initialize() {
		$this->model = I("model", "");
		$this->setControllerTitle('主题设置');
		$this->setActionTitle(array(
				'index' => '主题选择',
				'config' => '样式设置',
		));
	}
	
	/**
	 * 主题选择
	 */
	public function indexAction() {
		$model = M($this->model)->find($this->aid);
		$modelId = M("Model")->where("tag='{$this->model}'")->getField("id");
		$themeLists = M("Theme")->where(array('partner'=>array(array('eq',0),array('eq',$this->aid), 'or'), 'model_id'=>$modelId, 'status'=>1, 'is_deleted'=>0))
								->order("partner")->getField("id, image, config, name", true);
		foreach ($themeLists as &$v) $v['config'] = unserialize($v['config']);
		$this->assign("themeLists", $themeLists);
		$this->assign("themeId", $model['theme']);
		$this->display();
	}
	
	/**
	 *  本色设置
	 */
	public function configAction() {
		$themeId = I('id', 0, "intval");
		$theme = M("Theme")->find($themeId);
		$condition = array('pid' => $this->aid,
				'theme' => $theme['id']);
		$m = M("ThemeConfig");
		$themeConfig = $m ->where($condition)->find();
		if(!$themeConfig) {
			if($id = $m->add($condition) and $id===false) {
				$this->error("添加颜色配置失败");
				exit;
			}
			M($this->model)->where('id=%d and theme=%d', $this->aid, $themeId)->setField('theme_color', $id);
			$themeConfig = $m->find($id);
		}
		$all_config = unserialize($theme["config"]);
		$config = unserialize($themeConfig['config']);
		foreach ($all_config as &$v) $v["value"] = $config[$v['varName']]; // 绑定参数值
		$this->assign("config", $all_config);
		$this->assign("indexUrl", url('Home', 'Shop', 'index', "pid={$this->aid}&tid=$themeId"));
		$this->assign('theme', $theme);
		$this->display();
	}
	
	/**
	 * 设置主题
	 */
	public function setThemeAction() {
		$theme = I("theme", 0, "intval");
		false !== M($this->model)->where("id=%d", $this->aid)->setField("theme", $theme) and $this->ajaxSuccess("设为默认主题成功");
		$this->ajaxError("设置默认主题失败");
	}
	
	/**
	 * 提交设置
	 */
	public function savePostAction() {
		$themeId = I('id', 0, "intval");
		$d = D("ThemeConfig");
		$theme = M("Theme")->find($themeId);
		$themeConfig = array();
		$data = I("config");
		if(is_array($data)) {
			foreach ((array)unserialize($theme["config"]) as $v) {
				empty($data[$v["varName"]]) or $themeConfig[$v["varName"]] = $data[$v["varName"]];
			}
		}
		false !== $d->where(array('pid'=>$this->aid, 'theme' => $theme['id']))->setField("config", serialize($themeConfig)) and $this->ajaxSuccess("颜色配置成功");
		$this->ajaxError("颜色配置失败");
	}
}